package estore;
import java.io.Serializable;
import java.util.Objects;
import java.util.Set;
import java.util.HashSet;

public class Product implements Comparable<Product>, Serializable {
    // 添加serialVersionUID
    private static final long serialVersionUID = 1L;
    
    private String id;      // 商品ID
    private String name;    // 商品名称
    private double price;   // 价格
    private int stock;      // 库存
    private Set<String> tags; // 商品标签

    public Product(String id, String name, double price, int stock) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.stock = stock;
        this.tags = new HashSet<>(); // 初始化为空的HashSet
    }

    // 新增构造函数，支持传入标签集合
    public Product(String id, String name, double price, int stock, Set<String> tags) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.stock = stock;
        this.tags = (tags != null) ? new HashSet<>(tags) : new HashSet<>(); // 如果传入标签则复制，否则初始化为空的HashSet
    }

    // Getters and Setters ...
    public String getId() { return id; }
    public void setId(String id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }
    public int getStock() { return stock; }
    public void setStock(int stock) { this.stock = stock; }
    
    // 新增tags的getter和setter方法
    public Set<String> getTags() {
        return new HashSet<>(tags); // 返回副本，避免外部直接修改
    }
    
    public void setTags(Set<String> tags) {
        this.tags = (tags != null) ? new HashSet<>(tags) : new HashSet<>();
    }
    
    // 添加单个标签的方法
    public void addTag(String tag) {
        if (tag != null && !tag.trim().isEmpty()) {
            this.tags.add(tag);
        }
    }
    
    // 移除单个标签的方法
    public void removeTag(String tag) {
        if (tag != null) {
            this.tags.remove(tag);
        }
    }

    @Override
    public String toString() {
        String baseInfo = String.format("ID: %-5s | 名称: %-20s | 价格: ¥%-8.2f | 库存: %d", 
                                        id, name, price, stock);
        
        // 如果有标签，在末尾添加标签信息
        if (!tags.isEmpty()) {
            baseInfo += " | 标签: " + tags;
        }
        
        return baseInfo;
    }

    // 重写 equals 和 hashCode 是一个好习惯，特别是当对象要放入Set或作为Map的key时
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Product product = (Product) o;
        return Objects.equals(id, product.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    // 对商品进行排序，按照ID
    @Override
    public int compareTo(Product other) {
        return this.id.compareTo(other.id);
    }
}